package com.shycloud.mido.member.service.impl;

import java.time.LocalDateTime;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.member.api.entity.OrgStudentDetailed;
import com.shycloud.mido.member.api.entity.SmMemberTeacherRemark;
import com.shycloud.mido.member.mapper.SmMemberTeacherRemarkMapper;
import com.shycloud.mido.member.service.OrgStudentDetailedService;
import com.shycloud.mido.member.service.SmMemberTeacherRemarkService;
import com.shycloud.mido.member.service.TeacherService;

import lombok.AllArgsConstructor;

@Service
@AllArgsConstructor
public class SmMemberTeacherRemarkServiceImpl extends ServiceImpl<SmMemberTeacherRemarkMapper, SmMemberTeacherRemark> implements
		SmMemberTeacherRemarkService {

	/** 教师模块 */
	private TeacherService teacherService;
	/** 学生详情 service */
	private OrgStudentDetailedService studentDetailedService;

	/** 学生备注 mapper */
	private SmMemberTeacherRemarkMapper remarkMapper;

	/**
	 * 教师给学生设置备注
	 *
	 * @param remark
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/6/22 16:40
	 */
	@Override
	public Boolean remark(SmMemberTeacherRemark remark) {

		//根据学生ID获取机构ID
		OrgStudentDetailed studentDetailed = studentDetailedService.getOne(new QueryWrapper<OrgStudentDetailed>()
				.eq(OrgStudentDetailed.COL_ID, remark.getStudentId())
				.and(x -> x.eq(OrgStudentDetailed.COL_DEL_FLAG, "0")));

		String teacherId;

		//获取教师Id
		if (StringUtils.isNotBlank(remark.getTeacherId())) {
			teacherId = remark.getTeacherId();
		} else {
			teacherId = teacherService.getTeacher(studentDetailed.getOrgId(), SecurityUtils.getMember().getId()).getId();
		}

		//根据教师ID和学生ID查询备注信息来判断将要执行新增还是更新操作
		SmMemberTeacherRemark smMemberTeacherRemark = remarkMapper.selectOne(new QueryWrapper<SmMemberTeacherRemark>()
				.eq(SmMemberTeacherRemark.COL_STUDENT_ID, remark.getStudentId())
				.and(x -> x.eq(SmMemberTeacherRemark.COL_TEACHER_ID, teacherId)));

		//如果不为空，则进行更新操作
		if (smMemberTeacherRemark != null) {
			//昵称
			smMemberTeacherRemark.setShowName(remark.getShowName());
			//备注信息
			smMemberTeacherRemark.setRemark(remark.getRemark());
			//更新时间
			smMemberTeacherRemark.setUpdateTime(LocalDateTime.now());
			//更新操作
			remarkMapper.updateById(smMemberTeacherRemark);
		}

		//执行新增操作
		else {

			//创建时间
			remark.setCreateTime(LocalDateTime.now());
			//教师ID
			remark.setTeacherId(teacherId);
			//更新操作
			remarkMapper.insert(remark);
		}

		return true;
	}
}
